function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
	if (hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}

var load_video = function(url, ele) {
	ele.removeAttribute('data-src');
	mui.getJSON('http://t.fanheapp.com/get_video', {
		url: url
	}, function(response) {
		if (response.success) {
			var video_url = response.data.video;
			ele.setAttribute('src', video_url);
		} else {
			console.log('load error for url:' + url);
		}
	});
}

var appid = 'kou72um0ioak1kubrz0klwx8a7s3l261mgt54vbyotnblnby';
var appkey = 'o56bexx1vr522x7ygfkvi7efvbhhmo6x2oaf3txb75wi2509';
AV.initialize(appid, appkey);
var Banner = AV.Object.extend('Banner');
var Almanac = AV.Object.extend('Almanac');
var Feed = AV.Object.extend('Feed');

var storage = window.localStorage;

var preview_for = 0;

var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var yesterday = new Date();
yesterday.setTime(today.getTime() - 86400000);
var two_days_before = new Date();
two_days_before.setTime(today.getTime() - 2 * 86400000);
var three_days_before = new Date();
three_days_before.setTime(today.getTime() - 3 * 86400000);
var current_date = new Date();
var screen_width;
var scroll;

var render_daily = function(single_daily_data, date) {
	var daily_ele = document.createElement('div');
	daily_ele.className = "daily-ele";
	daily_ele.style.display = "none";
	document.getElementById("daily-content").appendChild(daily_ele);
	single_daily_data['width'] = screen_width;
	var daily_html = template('daily-tpl', single_daily_data);
	daily_ele.innerHTML = daily_html;
	daily_ele.style.display = "block";
	//异步加载老黄历的内容
	load_almanac(single_daily_data.feeds, date, daily_ele);
};

//加载最近的3天内容，用于下拉刷新和首次加载
var render_newest_daily = function() {
	//show newest daily data in storage
	if ('daily_array' in storage) {
		var newest_length = 3 + preview_for;
		var daily_array = JSON.parse(storage['daily_array']);
		console.log('start with storage, size:' + daily_array.length);
		if (daily_array.length < 3 + preview_for) {
			newest_length = daily_array.length
		}
		console.log("取出最新的" + newest_length + "天内容");
		for (var i = 0; i < newest_length; i++) {
			var daily_string = daily_array[daily_array.length - i - 1];
			var storage_key = 'daily_' + daily_string;
			var single_daily_data = JSON.parse(storage[storage_key]);
			var date = new Date();
			date.setTime(Date.parse(daily_string));
			date.setHours(0);
			render_daily(single_daily_data, date);
		}
	}
	current_date.setTime(two_days_before.getTime());
}

var load_almanac = function(feeds, date, dom_ele) {
	var almanac_query = new AV.Query(Almanac);
	almanac_query.equalTo('publishAt', date);
	almanac_query.descending('createdAt');
	almanac_query.first().then(function(ele) {
		var single_daily_data = {
			is_today: (date.getTime() == today.getTime()),
			date_pattern1: date.pattern("yyyy.MM.dd EEE"),
			date_pattern2: date.pattern("yyyy.MM.dd"),
			date_lunar: date.lunar(),
			almanac: ele.get('coverUrl'),
			almanac_id: ele.id,
			qian_count: ele.get('qianCounter'),
			share_content: ele.get('share'),
			feeds: feeds,
		};

		var date_string = date.pattern("yyyy-MM-dd");
		var daily_array = storage['daily_array'] ? JSON.parse(storage['daily_array']) : [];
		if (daily_array.indexOf(date_string) == -1) {
			daily_array.push(date_string);
			daily_array.sort();
			storage['daily_array'] = JSON.stringify(daily_array);
		}
		var daily_key = 'daily_' + date_string;
		storage[daily_key] = JSON.stringify(single_daily_data);
		if (dom_ele) {
			dom_ele.getElementsByClassName('almanac_img')[0].setAttribute('data-src', ele.get('coverUrl'));
			dom_ele.getElementsByClassName('almanac_img')[0].setAttribute('src', ele.get("coverUrl"));
			dom_ele.getElementsByClassName('share')[0].setAttribute('data-id', ele.id);
			//dom_ele.getElementsByClassName('pray')[0].getElementsByClassName('value')[0].innerText = ele.get('qianCounter');
			//load_img(2);
		}
	}, function(error) {
		console.log(error.message)
	});
};

//核心加载方法
var load_older_daily = function(from_date, limit, auto_render) {
	var next_date = new Date();
	next_date.setTime(from_date.getTime() - (limit - 1) * 86400000);
	next_date.setHours(0);
	next_date.setMinutes(0);
	next_date.setSeconds(0);
	next_date.setMilliseconds(0);

	//TODO 如果是今天则不用取到最大值
	if (from_date.pattern("yyyy-MM-dd") != today.pattern("yyyy-MM-dd") || preview_for > 0) {
		from_date.setHours(23);
		from_date.setMinutes(59);
		from_date.setSeconds(59);
	}

	var feed_query = new AV.Query(Feed);
	feed_query.equalTo('pushCondition', 'all');
	//feed_query.equalTo('code', '开发');
	feed_query.include('topic');
	feed_query.include(['topic.badge']);
	feed_query.include('frame');
	feed_query.descending('pushTime');
	feed_query.lessThanOrEqualTo("pushTime", from_date);
	feed_query.greaterThan('pushTime', next_date);
	feed_query.find().then(function(eles) {
		var date_feeds = {};
		for (var i = 0; i < eles.length; i++) {
			// 获得Date String
			var push_time = eles[i].get('pushTime');
			var day_string = push_time.getDate();
			var month_string = push_time.getMonth() + 1;
			if (day_string < 10) {
				var day_string = "0" + day_string;
			}
			if (month_string < 10) {
				var month_string = "0" + month_string;
			}
			var date_string = '' + push_time.getFullYear() + '-' + month_string + '-' + day_string;
			if (date_feeds[date_string] == undefined) {
				date_feeds[date_string] = [];
			}
			//如果是Topic
			if (eles[i].get("contentType") == "topic") {
				var topic_ele = eles[i].get('topic');
				var badge_logo = null;
				if (topic_ele.get("badge")) {
					badge_logo = topic_ele.get("badge").get("picActive");
					console.log(topic_ele.get("badge").get("name"))
				}
				var topic = {
					id: topic_ele.id,
					cover: topic_ele.get('coverStandard'),
					name: topic_ele.get('name'),
					description: topic_ele.get('description'),
					collection_count: topic_ele.get('recCounter'),
					width: screen_width,
					badge: badge_logo,
					type: "topic"
				};
				var source_count = 0;
				var sources = JSON.parse(topic_ele.get('sourceCounter'));
				for (var s in sources) {
					if (sources[s] != null) {
						source_count += sources[s];
					}
				}
				topic.frame_count = source_count;
				date_feeds[date_string].push(topic);
			};
			//如果是Frame
			if (eles[i].get("contentType") == "frame") {
				var frame_ele = eles[i].get('frame');
				var meta_data = JSON.parse(frame_ele.get('metaDataV2'));
				var title = frame_ele.get('head');
				if (title == null || title == undefined) {
					title = meta_data.title
				}

				var text = frame_ele.get('content');
				if (text == null || text == undefined) {
					text = meta_data.text;
				}

				//				if (text.length > 50) {
				//					text = text.slice(0, 47) + '...';
				//				}

				var content = meta_data.content;
				var imgs = [],
					long_tags = [],
					gif_tags = [];
				var video_covers = [];
				var cover_width = null,
					cover_height = null;

				for (var j = 0; j < content.length; j++) {
					if (content[j].type == 'photo' || content[j].type == 'gif') {
						var img_url = content[j].upyunUrl;
						imgs.push(img_url);
						long_tags.push(content[j].rawHeight / content[j].rawWidth > 3);
						gif_tags.push(content[j].type == 'gif');
					} else if (content[j].type == 'video') {
						var img_url = content[j].coverUrl;
						video_covers.push(img_url);
					}
				}
				var cover = frame_ele.get('coverUrl');

				var is_long = long_tags.length > 0 ? long_tags[0] : false;
				var is_square = false;
				if (cover == null || cover == undefined || cover == '') {
					if (imgs.length > 0) {
						cover = imgs[0];
						is_square = true;
					} else if (video_covers.length > 0) {
						cover = video_covers[0];
					}
				}

				var single_frame_data = {
					width: screen_width,
					id: frame_ele.id,
					style: frame_ele.get('style'),
					url: frame_ele.get('url'),
					title: title,
					author: frame_ele.get('author'),
					text: text,
					rec: frame_ele.get('title'),
					rec_count: frame_ele.get('recCounter'),
					cover: cover,
					is_square: is_square,
					is_long: is_long,
					imgs: imgs,
					meta_data: meta_data,
					long_tags: long_tags,
					gif_tags: gif_tags,
					type: "frame"
				}
				date_feeds[date_string].push(single_frame_data);
			}
		}

		for (var date_string in date_feeds) {
			var feeds = date_feeds[date_string];
			var date = new Date();
			date.setTime(Date.parse(date_string));
			date.setHours(0);

			var single_daily_data = {
				is_today: (date.getTime() == today.getTime()),
				date_pattern1: date.pattern("yyyy.MM.dd EEE"),
				date_pattern2: date.pattern("yyyy.MM.dd"),
				date_lunar: date.lunar(),
				almanac: '',
				almanac_id: '',
				qian_count: '',
				feeds: feeds,
			};

			if (auto_render) {
				render_daily(single_daily_data, date);
			} else {
				//提前缓存一个没有老黄历的数据版本，供下拉刷新渲染马上使用
				var daily_array = storage['daily_array'] ? JSON.parse(storage['daily_array']) : [];
				if (daily_array.indexOf(date_string) == -1) {
					daily_array.push(date_string);
					daily_array.sort();
					storage['daily_array'] = JSON.stringify(daily_array);
				}
				var daily_key = 'daily_' + date_string;
				storage[daily_key] = JSON.stringify(single_daily_data);
			}
		};
		if (!auto_render) {
			//清空原有的Daily内容，重新填充HTML
			document.getElementById("daily-content").innerHTML = "";
			render_newest_daily();
			setTimeout(function() {
				mui.toast("刷新成功");
			}, 500)
		}
		mui("video").each(function() {
			var url = this.getAttribute('data-src');
			var src = this.getAttribute('src');
			if (url) {
				console.log("Load Video Url: " + url);
				load_video(url, this);
			}
		});
	});
};

//用于上拉加载的函数
var render_older_daily = function() {
	//load_older_daily(current_date);
	for (var i = 0; i < 3; i++) {
		current_date.setTime(current_date.getTime() - 86400000);
		var date_string = current_date.pattern('yyyy-MM-dd');
		var storage_key = 'daily_' + date_string;
		var date = new Date();
		date.setTime(Date.parse(date_string));
		date.setHours(0);
		if (storage_key in storage) {
			var data = JSON.parse(storage[storage_key]);
			render_daily(data, date);
			if (i == 2) {
				mui("video").each(function() {
					var url = this.getAttribute('data-src');
					var src = this.getAttribute('src');
					if (url) {
						console.log("Load Video Url: " + url);
						load_video(url, this);
					}
				});
			}
		} else {
			var days_to_load = 3 - i;
			load_older_daily(current_date, days_to_load, true);
			current_date.setTime(current_date.getTime() - (days_to_load - 1) * 86400000);
			break;
		}
	}
	pollScroll();
};

mui.init({
//	pullRefresh: {
//		container: '#refreshContainer', //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
//		deceleration: 0.0015,
//		up: {
//			contentdown: "加载更多",
//			contentnomore: '就到这里啦',
//			callback: function() {
//				//最早就到16年1月15号
//				if (current_date < Date.parse("2016-01-15")) {
//					this.endPullupToRefresh(true);
//					mui.toast("没有更多啦");
//				} else {
//					setTimeout(function() {
//						render_older_daily();
//						mui('#refreshContainer').pullRefresh().endPullupToRefresh(false)
//					}, 1000)
//				}
//			}
//		},
//		down: {
//			callback: function() {
//				//current_date = new Date();
//				//load_older_daily(current_date, 3, false);
//				var now = new Date();
//				current_date.setTime(now.getTime() + preview_for * 86400000);
//				load_older_daily(current_date, 3 + preview_for, false);
//			}
//		}
//	}
});

function lowEnough() {
	var scroll_height = document.querySelector('#refreshContainer').scrollHeight; // 滚动条的高度
	var scroll_top = document.querySelector('#refreshContainer').scrollTop; // 滚动了多少像素
	var offset_height = document.querySelector('#refreshContainer').offsetHeight; // 偏移的高度
	return scroll_top >= scroll_height - offset_height - 3000;
}

function checkScroll() {
	if (!lowEnough()) return pollScroll();
	if (current_date < Date.parse("2016-01-14")) {
		mui.toast("没有更多啦");
	} else {
		console.log("无限再加点：" + current_date)
		render_older_daily();
		setTimeout(function() {
			scroll.refresh();
		}, 300)
	}
}

function pollScroll() {
	setTimeout(checkScroll, 1500);
}

var shares = {};
mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	screen_width = plus.screen.resolutionWidth;
	console.log('plus ready');
	//设定状态栏样式
	if (plus.navigator.isImmersedStatusbar() && mui.os.ios) {
		document.getElementById("bar-cover").style.display = 'block';
		document.getElementById("bar-cover").style.backgroundImage = "";
	}
	if (plus.navigator.isImmersedStatusbar() && mui.os.android) {
		document.getElementById("bar-cover").style.display = 'block';
		document.getElementById("bar-cover").style.backgroundColor = "";
	}

	//搞定分享列表
	plus.share.getServices(function(s) {
		if (s && s.length > 0) {
			for (var i = 0; i < s.length; i++) {
				var t = s[i];
				shares[t.id] = t;
			}
		}
	}, function() {
		console.log("获取分享服务列表失败");
	});
	
	//Render Daily Data
	render_newest_daily();
	//Pull Down Once
	var now = new Date();
	current_date.setTime(now.getTime() + preview_for * 86400000);
	load_older_daily(current_date, 3 + preview_for, false);

	scroll = new IScroll('#refreshContainer', {
		scrollbars: true,
		mouseWheel: true,
		deceleration: 0.001,
		shrinkScrollbars: "clip",
	});
	
	checkScroll();
});

var banner_query = new AV.Query(Banner);
banner_query.equalTo('hidden', false);
banner_query.descending('updatedAt');
banner_query.include('topic');
banner_query.find().then(function(eles) {
	var sliders = [];
	for (var i = 0; i < eles.length; i++) {
		var type = eles[i].get('bannerType')
		sliders.push({
			id: type == 'topic' ? eles[i].get('topic').id : -1,
			type: type,
			cover: eles[i].get('coverUrl'),
			url: eles[i].get('url'),
			name: type == 'topic' ? eles[i].get('topic').get('name') : '',
			description: type == 'topic' ? eles[i].get('topic').get('description') : '',
		});
	}

	var slider_html = template('slider-tpl', {
		sliders: sliders,
		width: screen_width
	});
	document.getElementById("slider").innerHTML = slider_html;
	var swiper = new Swiper('.swiper-container', {
		loop: true,
		autoplay: 2500,
		pagination: '.swiper-pagination',
	})
}, function(error) {
	console.log(error.message);
});

mui('body').on('tap', '.frame.card .cover', function(e) {
	e.stopPropagation();
	var id = this.getAttribute('data-id');
	var video = document.getElementById("video-" + id);
	var video_url = video.src;
	if (plus.networkinfo.getCurrentType() > 3) {
		plus.nativeUI.confirm('饭盒喵检测您正在移动网络下，播放视频需要大量流量喂喵', function(e) {
			if (e.index == 0) {
				if (plus && video_url) {
					if (mui.os.ios) {
						plus.nativeUI.showWaiting("加载链接中", {
							modal: false
						});
						video.onplay = function() {
							plus.nativeUI.closeWaiting();
						};
						video.onclose = function() {
							plus.nativeUI.closeWaiting();
						};
						video.play();
					} else {
						var Intent = plus.android.importClass("android.content.Intent");
						var Uri = plus.android.importClass("android.net.Uri");
						var main = plus.android.runtimeMainActivity();
						var intent = new Intent(Intent.ACTION_VIEW);
						var uri = Uri.parse(video_url);
						intent.setDataAndType(uri, "video/*");
						main.startActivity(intent);
					}
				} else {
					mui.toast("链接可能失效，饭盒喵会尽快处理！");
				}
			}
		}, '确定播放？', ['继续观看', '等会再看']);
	} else {
		if (plus && video_url) {
			if (mui.os.ios) {
				plus.nativeUI.showWaiting("加载链接中", {
					modal: false
				});
				video.onplay = function() {
					plus.nativeUI.closeWaiting();
				};
				video.onclose = function() {
					plus.nativeUI.closeWaiting();
				};
				video.play();
			} else {
				var Intent = plus.android.importClass("android.content.Intent");
				var Uri = plus.android.importClass("android.net.Uri");
				var main = plus.android.runtimeMainActivity();
				var intent = new Intent(Intent.ACTION_VIEW);
				var uri = Uri.parse(video_url);
				intent.setDataAndType(uri, "video/*");
				main.startActivity(intent);
			}
		} else {
			mui.toast("链接可能失效，饭盒喵会尽快处理！");
		}
	}
});

mui('body').on('tap', '[data-role=topic]', function() {
	var fid = this.getAttribute('data-id');
	mui.openWindow({
		id: 'topic',
		url: 'topic.html',
		styles: {
			top: 0,
			bottom: 0,
			bounce: 'vertical',
		},
		extras: {
			topic_id: fid,
		},
		show: {
			autoShow: true,
			aniShow: 'pop-in',
			duration: 300,
		},
		waiting: {
			autoShow: false,
		}
	});
});

mui('body').on('tap', '[data-role=frame]', function() {
	var fid = this.getAttribute('data-id');
	mui.openWindow({
		id: 'frame',
		url: 'frame.html',
		styles: {
			top: 0,
			bottom: 0,
			bounce: 'vertical',
		},
		extras: {
			frame_id: fid,
		},
		show: {
			autoShow: true,
			aniShow: 'pop-in',
			duration: 300,
		},
		waiting: {
			autoShow: false,
		}
	});
});

var share_id;
var share_icons;
var icon_is_show = false;
mui('#daily-content').on('tap', '.daily .share', function(e) {
	e.stopPropagation();
	share_id = this.getAttribute('data-id');
	share_icons = this.parentElement.getElementsByClassName('share-icons')[0];
	if (hasClass(share_icons, 'in')) {
		removeClass(share_icons, 'in');
		addClass(share_icons, 'out');
		share_icons.style.display = 'none';
		icon_is_show = false;
	} else {
		removeClass(share_icons, 'out');
		addClass(share_icons, 'in');
		share_icons.style.display = 'block';
		icon_is_show = true;
	}
});

mui('#daily-content').on('tap', '.share-icons .icon', function(e) {
	e.stopPropagation();
});

mui('body').on('tap', '*', function(e) {
	if (icon_is_show) {
		removeClass(share_icons, 'in');
		addClass(share_icons, 'out');
		share_icons.style.display = 'none';
		icon_is_show = false;
	}
});

mui('#daily-content').on('tap', '.share-icons .icon', function() {
	//DQ：Maybe 提前缓存好？
	var id = this.getAttribute('data-id');
	var type = this.getAttribute('data-type');
	var almanac = new Almanac();
	almanac.id = share_id;
	almanac.fetch().then(function(ele) {
		var content = ele.get('share');
		var msg = {};
		//TODO: 使用本地的老黄历图片
		var web_url = ele.get('coverUrl');
		var share_url = web_url;
		if (mui.os.android) {
			share_url = storage['img_' + web_url];
		}

		msg.content = content;
		msg.pictures = [share_url];
		if (type == "weixin-session") {
			msg.extra = {
				scene: "WXSceneSession"
			}
		}
		if (type == "weixin-timeline") {
			msg.extra = {
				scene: "WXSceneTimeline"
			}
		}
		var share = shares[id];
		if (share) {
			if (share.authenticated) {
				console.log("正在分享到" + share.description);
				share.send(msg, function() {
					mui.toast("分享到" + share.description + "成功");
				}, function(e) {
					mui.toast("分享到" + share.description + "失败");
					console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
				});
			} else {
				share.authorize(function() {
					share.send(msg, function() {
						mui.toast("分享到" + share.description + "成功！ ");
					}, function(e) {
						mui.toast("分享到" + share.description + "失败");
						console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
					});
				}, function(e) {
					mui.toast("认证授权失败" + e.message);
					console.log("认证授权失败：" + e.code + " - " + e.message);
				});
			}
		} else {
			mui.toast("无法获取分享服务");
		}
	}, function(error) {
		console.log('error when fetch almanac to share');
	});
});